//
//  MYDiscoverSearchView.swift
//  MYSinaWeico
//
//  Created by Magic Yu on 16/4/6.
//  Copyright © 2016年 Magic Yu. All rights reserved.
//

import UIKit

class MYDiscoverSearchView: UIView {

    @IBOutlet weak var searchTF: UITextField!
    
    @IBOutlet weak var cancelBtn: UIButton!
    
    @IBOutlet weak var rightConstraint: NSLayoutConstraint!
    
    
    override func awakeFromNib() {
        
        //设置frame
        //+[MYSinaWeico.MYDiscoverSearchView bounds]: unrecognized selector sent to class 0x105c7bc70'
        //约束设置不对 重新设置一下
        self.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: self.bounds.height)
    
        //设置左侧图片
        searchTF.leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        //设置frame  图片太靠左边,修改图片的frame,让宽与高相等,这样在center的模式下,图片就会居中显示,拉开与左边的距离
        searchTF.leftView?.frame = CGRect(x: 0, y: 0, width: self.bounds.height, height: self.bounds.height)
        searchTF.leftView?.contentMode = .Center
        searchTF.leftViewMode = .Always
        
        //设置文本框圆角
//        searchTF.layer.cornerRadius = 8
//        searchTF.layer.masksToBounds = true
       
    }
    
    //类方法创建
    class func loadSearchView() -> MYDiscoverSearchView {
        
        let v = NSBundle.mainBundle().loadNibNamed("MYDiscoverSearchView", owner: nil, options: nil).last as! MYDiscoverSearchView
        return v
        
    }
    
    //自动布局的动画执行
    //1.修改约束
    //2.在动画闭包中强制刷新界面
    @IBAction func beginEditing(sender: AnyObject) {
        
        //修改约束
        //系统只是收集了约束的变化 会在layoutsubviews方法中更新界面
        rightConstraint.constant = cancelBtn.frame.width
        
        //在动画闭包中强制刷新界面
        UIView.animateWithDuration(0.25) { () -> Void in
            //layoutIfNeeded是根据自动布局来修改frame
            self.layoutIfNeeded()
            self.cancelBtn.hidden = false
        }
        
        
    }
    
    @IBAction func cancelClick(sender: AnyObject) {
        //退出第一响应者
        searchTF.resignFirstResponder()
        //修改约束
        rightConstraint.constant = 0
        //刷新界面
        UIView.animateWithDuration(0.25) { () -> Void in
            self.cancelBtn.hidden = true
            self.layoutIfNeeded()
        }
    }

}



